<?php
/* ******************************
 *	Printer aJax actions
 * ******************************
 */

set_time_limit(0);

include('../../includes/classes/core.php');
 
include('../../includes/classes/category.tree.class.php');

$action		= $_REQUEST['act'];
$error		= '';
$data		= '';
$user_id	= $_SESSION['USERID'];


switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $prod_id	= $_REQUEST['id'];
		$page		= GetPage(GetProduct($prod_id));
        
        $data 		= array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    
	    $rResult = mysql_query("SELECT 		`PR`.`id`,
											`PR`.`code`,
											`PR`.`name`,
											`UN`.`name`,
											`CAT`.`name`,
											`PR`.`min_amount`
								FROM 		`production` AS `PR`
								LEFT JOIN 	`production_category` AS `CAT` ON `PR`.`category` = `CAT`.`id`
								LEFT JOIN 	`production_unit` AS `UN`  ON `PR`.`unit` = `UN`.`id`
								WHERE		`PR`.`id` in (SELECT `production_id` FROM `printer_identity`) && `PR`.`actived` != 0 && `PR`.`actived` != 2");
		
		$data = array(
			"aaData"	=> array()
		);
		
		while ( $aRow = mysql_fetch_array( $rResult ) )
		{
			$row = array();
			for ( $i = 0 ; $i < $count ; $i++ )
			{
				/* General output */
				$row[] = $aRow[$i];
				if($i == ($count - 1)){
					$row[] = '<input type="checkbox" name="check_' . $aRow[$hidden] . '" class="check" value="' . $aRow[$hidden] . '" />';
				}
			}
			$data['aaData'][] = $row;
		}
		

		
        break;
    case 'save_prod':
		$prod_id 	= $_REQUEST['id'];
		
		$arr = array(
				//Main
				'code'				=> htmlspecialchars($_REQUEST['cod'], ENT_QUOTES),
				'part_number'		=> htmlspecialchars($_REQUEST['pn'], ENT_QUOTES),
				'name'				=> htmlspecialchars($_REQUEST['n'], ENT_QUOTES),
				
				'type'				=> $_REQUEST['ty'],
				'amount'			=> $_REQUEST['am'],
				
				'category'			=> $_REQUEST['cat'],
				'unit'				=> $_REQUEST['un'],
				'country'			=> $_REQUEST['cy'],
				
				'page_resource'		=> $_REQUEST['pr'],
				'job_circle'		=> $_REQUEST['jc'],
				'min_amount'		=> $_REQUEST['min'],
				
				'comment'			=> htmlspecialchars($_REQUEST['c'], ENT_QUOTES),
				'image'				=> $_REQUEST['img']
		);
		
		if(!CheckProductExist($prod_id, $arr['name'])){
			SaveProduct($prod_id, $user_id, $arr);
		} else {
			$error = '"' . $arr['name'] . '" უკვე არის სიაში!';
		}
		
        break;
    case 'disable':
		$prod_id = $_REQUEST['id'];
		DisablePrinter($prod_id);
		
        break;
    case 'delete_image':
		$prod_id 		= $_REQUEST['id'];
		DeleteImage($prod_id);		
		
        break;
    case 'get_local_id':
		$local_id = GetLocalID($user_id);
		
		$data = array('local_id' => $local_id);
        
        break;
	case 'create_list':
		$local_id = $_REQUEST['id'];
		CreateList($local_id, $user_id);
		
        break;
	case 'check_list':
		$id 		= $_REQUEST['id'];
		$check		= ChackList($id);
		if($check){
			$error = 'თავსებადი ნაწილების სია ცარიელია! (გთხოვთ დაამატოთ მინიმუმ ერთი!)';
		}
		
        break;
    case 'clear':
		$file_list = $_REQUEST['file'];
		ClearProduct();
		if (!empty($file_list)) {
			$file_list = ClearFiles(json_decode($file_list));
		}
		$data = array('file_list' => json_encode($file_list));
		
        break;
    case 'clear_db':
    	
		ClearDB();
		
        break;
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Printer Functions
 * ******************************
 */

function ClearProduct() {
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM	`production`");
    
    while( $res = mysql_fetch_assoc($req)){
    	$name = htmlspecialchars($res[name], ENT_QUOTES);
    	mysql_query("	UPDATE
							`production`
						SET
							`name`	= '$name'
						WHERE
							`id`	= $res[id]");
    }
}

function ClearFiles($file_list) {
	$array = array();
	foreach ($file_list as $file) {
		if($file != '0.jpg' && $file != 'index.html'){
			$req = mysql_query("SELECT	`id`
					FROM	`production`
					WHERE	`image` = '$file'");
			if (mysql_num_rows($req) == 0){
				$array[] = $file;
			}
		}
	}
	return $array;
}

function ClearDB()
{
	$req = mysql_query("SELECT	`id`
						FROM	`printer_identity`
						WHERE	`production_id` NOT IN (SELECT `id` FROM `production`)");
	
	while( $res = mysql_fetch_assoc($req)){
		mysql_query("	DELETE
						FROM
							`printer_identity`
						WHERE `id` = $res[id]");
	}
}

function SaveProduct($id, $user_id, $arr)
{
	$result = mysql_query("INSERT IGNORE INTO `production` (`id`) VALUES ($id)");
	if(!$result){
		$error = 'Invalid query: ' . mysql_error();
	}else{
		mysql_query("	UPDATE
							`production`
						SET
						    `user_id`		= $user_id,
						    `code`			= '$arr[code]',
						    `part_number`	= '$arr[part_number]',
						    `name`			= '$arr[name]',
						    `country`		= $arr[country],
						    `category`		= $arr[category],
						    `unit`			= $arr[unit],
						    `min_amount`	= $arr[min_amount],
						    `page_resource`	= $arr[page_resource],
						    `job_circle`	= $arr[job_circle],
						    `image`			= '$arr[image]',
						    `comment`		= '$arr[comment]',
						    `actived`		= 1
						WHERE
							`id`			= $id");
	}
}

function CheckProductExist($prod_id, $prod_name) 
{
    $res = mysql_fetch_assoc(mysql_query("	SELECT	`id`
										  	FROM	`production`
										  	WHERE	`name` = '$prod_name' && `actived` = 1 && `id` != $prod_id"));
	if($res['id'] != ''){
		return true;
	}
	return false;
}

function DisablePrinter($prod_id)
{
    mysql_query("	UPDATE	`production`
				    SET		`actived`	= 0
				    WHERE	`id` = $prod_id");
}

function GetLocalID()
{
	GLOBAL $db;
	$local_id = $db->increment('production');
	
	return $local_id;
}

function CreateList($id, $user_id)
{
	$req = mysql_query("SELECT	`id`
						FROM	`printer_parts_type`
						WHERE	`default` = 1");

	while( $res = mysql_fetch_assoc($req)){
		mysql_query("	INSERT INTO `printer_identity`
							(`user_id`, `production_id`, `parts_type`) 
				 		VALUES
							($user_id, $id, $res[id])");
	}
}

function ChackList($id)
{
	$check = false;
	$req = mysql_query("SELECT	`production_id`
						FROM	`printer_identity`
						WHERE	`production_id` = $id");

	if (mysql_num_rows($req) == 0){
		$check = true;
	}

	return $check;
}

function DeleteImage($prod_id)
{
	mysql_query("UPDATE
	    			`production`
				 SET
				    `image`		= NULL
				 WHERE
					`id`		= $prod_id");
}

function GetSize($point)
{
	$data = '';
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM	`production_unit`");
										
	if($point == ''){
		$data = '<option value="0" selected="selected"></option>';
	}
			
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
		
	return $data;
}

function GetCategory($point)
{
	$data = '';
	
	$data = '<option value="0" selected="selected"></option>';	
	$tree = new CategoryTree($point);
	$tree->SetParent(7);
	$data .= $tree->GetData();
	
	return $data;
}

function GetCountry($point)
{
	$data = '';
    $req = mysql_query("SELECT	`id`,
    							`name`
						FROM	`country`");
	
	$data = '<option value="0" selected="selected"></option>';
		
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $point){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
		
	return $data;
}

function GetProduct($prod_id) 
{
    $res = mysql_fetch_assoc(mysql_query("	SELECT	`id`,
													`code`,
    												`part_number`,
													`name`,
													`category`,
													`unit`,
    												`country`,
    												`page_resource`,
    												`job_circle`,
													`min_amount`,
													`image`,
    												`comment`
											FROM	`production`
											WHERE	`id` = $prod_id"));
	return $res;
}

function GetPage($res = '')
{
	$image = $res[image];
	if(empty($image)){
		$image = '0.jpg';
	}
	$data = '
	<!-- jQuery Dialog -->
    <div id="add-edit-ident-form" class="form-dialog" title="შემადგენლობა">
    	<!-- aJax -->
	</div>
	<div id="dialog-form">
		<fieldset style="width: 350px; float: left;">
	    	<legend>ძირითადი ინფორმაცია</legend>

	    	<table class="dialog-form-table">
	    		<tr>
					<td style="width: 170px;"><label for="code">კოდი</label></td>
					<td>
						<input type="text" id="code" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['code'] . '" />
					</td>
				</tr>
	    		<tr>
					<td style="width: 170px;"><label for="part_number">Part Number</label></td>
					<td>
						<input type="text" id="part_number" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['part_number'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="name">დასახელება</label></td>
					<td>
						<input type="text" id="name" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['name'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="prod_category">კატეგორია</label></td>
					<td>
						<select id="prod_category" class="idls">' . GetCategory($res[category]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="unit">ზომის ერთეული</label></td>
					<td>
						<select id="unit" class="idls num">' . GetSize($res[unit]) . '</select>
					</td>
				</tr>
			</table>
        </fieldset>
 	    <fieldset style="width: 350px; float: right;">
	    	<legend>პროდუქტის სურათი</legend>
			
	    	<table class="dialog-form-table" width="100%">
	    		<tr>
					<td id="img_colum" colspan="2">
						<img id="upload_img" src="media/uploads/images/production/' . $image . '">
					</td>
				</tr>
				<tr><!-- Upload Image -->
					<td id="act">
						<span>
							<a href="#" id="view_image" class="complate">View</a> | <a href="#" id="delete_image" class="delete">Delete</a>
						</span>
					</td>
					<td>
						<div class="file-uploader">
							<input id="choose_file" type="file" name="choose_file" class="input" style="display: none;">
							<button id="choose_button" class="center">აირჩიეთ ფაილი</button>
						</div>
					</td>
				</tr>
			</table>
        </fieldset>
		<div class="clear"></div>
		<fieldset style="width: 350px; float: left;">
	    	<legend>დამატებითი ინფორმაცია</legend>

	    	<table class="dialog-form-table">
				<tr>
					<td style="width: 170px;"><label for="country">ქვეყანა</label></td>
					<td>
						<select id="country" class="idls">' . GetCountry($res[country]) . '</select>
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="page_resource">გვერდების რესურსი</label></td>
					<td>
						<input type="text" id="page_resource" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['page_resource'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="job_circle">სამუშაო ციკლი</label></td>
					<td>
						<input type="text" id="job_circle" class="idle" onblur="this.className=\'idle\'" onfocus="this.className=\'activeField\'" value="' . $res['job_circle'] . '" />
					</td>
				</tr>
				<tr>
					<td style="width: 170px;"><label for="min_amount">მინ. რაოდენობა</label></td>
					<td>
						<input type="text" id="min_amount" class="idle num" onblur="this.className=\'idle num\'" onfocus="this.className=\'activeField num\'" value="' . $res['min_amount'] . '" />
					</td>
				</tr>
			</table>
        </fieldset>
		<fieldset style="width: 350px; float: right;">
	    	<legend>შენიშვნა</legend>

	    	<table class="dialog-form-table" style="height: 120px;">
				<tr>
					<td valign="top">
						<textarea id="comment" class="idle large" cols="40" rows="6">' . $res['comment'] . '</textarea>
					</td>
				</tr>
			</table>
        </fieldset>
		<div class="clear"></div>
		<fieldset>
	    	<legend>თავსებადი ნაწილები</legend>

		    <div class="inner-table">
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" class="overhead_container">
			        	<div id="button_area">
			        		<button id="add_button_part">დამატება</button><button id="delete_button_part">წაშლა</button>
			        	</div>
			            <div id="dynamic">
			                <table class="display" id="ident_list">
			                    <thead>
			                        <tr id="datatable_header">				                        
			                            <th>ID</th>
			                            <th style="width: 100%;">ტიპი</th>
			                            <th style="width: 170px;">კატეგორია</th>
			                            <th style="width: 50px;">რაოდ.</th>
			                            <th class="check">#</th>
			                        </tr>
			                    </thead>
			                    <thead>
			                        <tr class="search_header">				                        
			                            <th class="colum_hidden">
			                            	<input type="text" name="search_id" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th>
			                            	<input type="text" name="search_prod" value="ფილტრი" class="search_init" />
			                            </th>
			                            <th></th>
										<th>
											<input type="checkbox" name="check-all" id="check-all-part">
										</th>
			                        </tr>
			                    </thead>
			                </table>
			            </div>
			        </div>
			    </div>
			</div>
		</fieldset>
		<!-- ID -->
		<input type="hidden" id="prod_id" value="' . $res['id'] . '" />
    </div>';
	
	return $data;
}
?>